package com.igeek.ch01;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @package com.igeek.ch01
 * @Description
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/11/15 13:57
 */
@Component
public class MyAware implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("bean = " + bean.getClass());
        if (bean instanceof ICount){
            ICount proxy = (ICount) Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            //开启日志追踪  前置通知
                            System.out.println("开启日志追踪 method="+method.getName()+",args="+ Arrays.toString(args));
                            //返回通知
                            Object result  = null;
                            try {
                                result = method.invoke(bean, args);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            //执行目标方法  后置通知
                            System.out.println("结束日志追踪 method="+method.getName()+",result="+result);
                            return result;
                        }
                    }
            );
            System.out.println("proxy = " + proxy.getClass());
            return proxy;
        }
        return bean;
    }
}
